package at.fhooe.im440.pandora.graphicsConfig;

import java.awt.Graphics2D;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import at.fhooe.im440.core.Core;
import at.fhooe.im440.pandora.logic.entities.Entity;
import at.fhooe.im440.pandora.logic.entities.EntityManager;

public class GraphicsSystem {

	private RenderSystem renderSystem;
	private Core core;
	private Map<String, Entity> objects;

	//private static GraphicsSystem instance;

	private int width;
	private int height;

	public GraphicsSystem(Core core) {
		this.core = core;
		objects = new HashMap<String, Entity>();
		renderSystem = new RenderSystem();
		renderSystem.addKeyListener(core.keyboardMgr);
	}

	public void addKeyListener(KeyListener k){
		renderSystem.addKeyListener(k);
	}
	
	public void addEntity(Entity entity) {
		objects.put(entity.getName(), entity);
	}

	public void removeEntity(String name) {
		objects.remove(name);
	}

	public void open(int width, int height, boolean fullscreen) {
		this.width = width;
		this.height = height;
		renderSystem.open(width, height, fullscreen, core);
	}

	public void render() {
		Graphics2D g = renderSystem.beginUpdate();
		g.clearRect(-width / 2, -height / 2, width, height);
		
	//	c.entityMgr.updateEntities();
		//core.entityMgr.renderEntities(g);
		for(EntityManager e: core.entityMgrs){
			e.renderEntities(g);
		}
		
		renderSystem.endUpdate();
	}

	public Entity getEntity(String name) {
		if (objects.containsKey(name)) {
			return objects.get(name);
		} else {
			return null;
		}
	}

	public ArrayList<Entity> getEntitiesWithNameLike(String name) {
		ArrayList<Entity> returnList = new ArrayList<Entity>();
		Object[] keySet = objects.keySet().toArray();

		for (Object key : keySet) {
			if (((String) key).contains(name)) {
				returnList.add(objects.get(key));
			}
		}
		return returnList;
	}

	public void setFrameRate(int fps) {
		renderSystem.setFrameRate(fps);
	}

	public void close() {
		renderSystem.close();
	}

}
